package net.sharpf2.api.interfaces;

import net.sharpf2.sfcore.client.Interface;
import net.sharpf2.api.types.Content;

import java.util.ArrayList;
import net.sharpf2.api.game.Interfaces;
import net.sharpf2.api.info.Item;

/**
 * @author Drew Lindsey
 */

public class Shop {
    
    /**
     * Gets the shop interface
     * @return The shop interface
     */

    public static Content<Interface> getInterface() {
        return Interfaces.get(Constants.SHOP_INTERFACE, 0);
    }
    
    /**
     * Checks if interface is open.
     * @return true if interface is opened, oteherwise false.
     */
    
    public static boolean isOpen() {
        return getInterface() != null;
    }

    /**
     * Gets the item array of the shop
     * @return  Array of items in the shop
     */

    public static Item[] getItems() {
        ArrayList<Item> items = new ArrayList<Item>();
        Interface[] itemComponents = Interfaces.get(Constants.SHOP_INTERFACE, Constants.INVENTORY_INTERFACE).getContent().getChildren();
        for(Interface child : itemComponents) {
            if(child != null && child.getId() > 0) {
                items.add(new Item(new Content<Interface>(child)));
            }
        }
        return items.toArray(new Item[items.size()]);
    }

    /**
     * Gets the first item with specified ids
     * @param   ids  accepted ids
     * @return  First item with the given ID, otherwise null.
     */

    public static Item getItem(int... ids) {
        for(Item item : getItems()) {
            for(int id : ids) {
                if(item.getId() == id) {
                    return item;
                }
            }
        }
        return null;
    }

    /**
     * Buys an item
     * @param id        id of the item to buy
     * @param amount    amount of item to buy
     */
    public static void buyItem(int id, int amount) {
        Item item = getItem(id);
        for (String it : item.getContent().getActions()) {
            if (it.contains("(Buy-" + amount + "|" + amount + " kaufen|Acheter " + amount + ")")) {
                item.interact("(Buy-" + amount + "|" + amount + " kaufen|Acheter " + amount + ")");
            } else {
                //TODO: automated system.
            }
        }
    }

    public class Constants {
        public static final int SHOP_INTERFACE = 620;
        public static final int BUTTON_CLOSE = 18;
        public static final int INVENTORY_INTERFACE = 25;
    }

}
